package com.xiaoxu.springboot.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ViewMappingInterceptor implements HandlerInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(ViewMappingInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.debug("===pre interceptor====");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("===post===");
        //判断请求是否为接口，如果为接口直接返回
        if (modelAndView==null){
            return;
        }

        //判断页面请求是否为重定向或者请求转发，如果是返回
        if (modelAndView.getViewName().startsWith("redirect") || modelAndView.getViewName().startsWith("forward")){
            return;
        }
        //获取请求路径
        String path=request.getContextPath();
        //判断modelMap是否有template，有则跳过，无则设置
        String template=(String)modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(template)){
            modelAndView.getModelMap().addAttribute("template",path.substring(1,path.length()));
        }
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("===after===");
    }
}
